package com.minivision.fdiot.service;

import java.util.List;
import java.util.stream.Collectors;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cloud.client.ServiceInstance;
import org.springframework.cloud.client.discovery.DiscoveryClient;
import org.springframework.core.env.Environment;
import org.springframework.stereotype.Service;

import com.minivision.fdiot.util.ServiceUtils;

/**
 * 获取动态服务节点
 * @author hughzhao
 * @2018年3月1日
 */
@Service 
public class DiscoveryService {
  
  @Autowired
  private DiscoveryClient discoveryClient;
  
  @Autowired
  private Environment environment;
  
  /**
   * 获取动态服务节点
   * @return
   */
  public List<String> getServiceNodes() {
    List<ServiceInstance> instances = discoveryClient.getInstances(environment.getProperty("spring.application.name"));
    return instances.stream().map(instance -> ServiceUtils.getServiceNode(instance)).collect(Collectors.toList());
  }
  
  /**
   * 获取动态服务节点URL
   * @return
   */
  public List<String> getServiceUrls() {
    List<ServiceInstance> instances = discoveryClient.getInstances(environment.getProperty("spring.application.name"));
    return instances.stream().map(instance -> ServiceUtils.getServiceUrl(instance)).collect(Collectors.toList());
  }
  
  /**
   * 服务节点是否在线
   * @param node
   * @return
   */
  public boolean isUp(String node) {
    List<String> nodes = getServiceNodes();
    return nodes.contains(node);
  }

}
